package json;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;




import org.junit.Test;

import service.model.User;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;



/**
 * @author E440
 *
 */
/**
 * @author E440
 *
 */
public class FastJsonDemo {
	private static SerializeConfig mapping = new SerializeConfig(); static { 
	    mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 
	  } 
	
	private class P1{
		private String name;
		private Date date;
		P1(){}
		P1(String name,Date date){
			this.name=name;
			this.date=date;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Date getDate() {
			return date;
		}
		public void setDate(Date date) {
			this.date = date;
		}
	}
	
	private class P2{
		private String name;
		@JSONField (format="yyyy-MM-dd HH:mm:ss") 
		private Date date;
		
		P2(){}
		P2(String name,Date date){
			this.name=name;
			this.date=date;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Date getDate() {
			return date;
		}
		public void setDate(Date date) {
			this.date = date;
		}
	}
	
	
	/*对日期的序列化：一种方法是通过注解;另一种是通过SerializeConfig*/
	@Test
	public void date2Json(){
		 Date date = new Date(); 
		 String text = JSON.toJSONString(date, mapping);
		 Map<String,Object> map=new HashMap<String, Object>();
		 map.put("birthday", date);
		 map.put("x", "1");
		 String mapString=JSON.toJSONString(map,mapping);
		 System.out.println("**********  original ***********");
		 System.out.println(JSON.toJSONString(date));
		 System.out.println("**********  new Date() ***********");
		 System.out.println(text);
		 System.out.println("**********  Map[x=1;birthday=new Date()] ***********");
		 System.out.println(mapString);
		 
		 P1 p1=new P1("nsl", new Date());
		 String p1sString=JSON.toJSONString(p1,mapping);
		 System.out.println("**********  P1[name=nsl;birthday=new Date()] ***********");
		 System.out.println(p1sString);		
		 
		 P2 p2=new P2("djj", new Date());
		 String p2sString=JSON.toJSONString(p2);
		 System.out.println("**********  P2[name=djj;birthday=new Date()] ***********");
		 System.out.println(p2sString);	
	}
	
	@Test
	public void json2Date(){
		String j1="{\"birthday\":\"2016-04-19\",\"name\":\"1\"}";
		//String j1="{\"name\":\"1\"}";
		User user= JSON.parseObject(j1,User.class);
		System.out.println(user);
	}
	
}
